package com.xiaohuitalk.tools.util;

import com.xiaohuitalk.tools.exception.CocoException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by xiaohuitalk on 2016/9/15.
 */
public class DateUtil {

    public static final String PATTERN_DATE = "yyyy-MM-dd";
    public static final String PATTERN_DATETIME = "yyyy-MM-dd hh:mm:ss";

    private DateUtil() {

    }

    private static ThreadLocal<SimpleDateFormat> deteFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(PATTERN_DATE);
        }
    };

    /**
     * 格式化成默认样式（yyyy-MM-dd）
     */
    public static String formart(Date date) {
        SimpleDateFormat sdf = deteFormatThreadLocal.get();
        return sdf.format(date);
    }

    /**
     * 根据默认样式解析（yyyy-MM-dd）
     */
    public static Date parse(String str) {
        SimpleDateFormat sdf = deteFormatThreadLocal.get();
        try {
            return sdf.parse(str);
        } catch (ParseException e) {
            throw new CocoException("== 解析时间错误", e);
        }
    }

    /**
     * 根据指定样式格式化
     */
    public static String formart(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }


    /**
     * 根据指定样式样式解析
     */
    public static Date parse(String str, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(str);
        } catch (ParseException e) {
            throw new CocoException("== 解析时间错误", e);
        }
    }

}
